package com.ishitong.platform.utils.controller;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtilsBean;

import com.ishitong.platform.common.page.Page;
import com.ishitong.platform.common.page.PageBar;


/**
 * @功能描述：spring mvc 基础控制器
 * @author liufeng
 * @date:2013/7/11
 */
public abstract class SpringBaseController {

	private static final Integer defaultPageSize=15;//默认每页记录数
	static{
	  ConvertUtilsBean convertUtilsBean= BeanUtilsBean.getInstance().getConvertUtils();
	  ConvertRegisterHelper.registerConverters(convertUtilsBean,new String[]{"yyyy-MM-dd"});
	}
	/**
	 * 获得每页记录条数
	 * @param request
	 * @return
	 */
	protected Integer getPageSize(HttpServletRequest request)
	{
		String pageSize=request.getParameter("query.pageSize");
		if(pageSize!=null&&!pageSize.trim().equals(""))
		{
			return Integer.parseInt(pageSize);
		}
		return defaultPageSize;
	}
	/**
	 * 获得当前页
	 * @param request
	 * @return
	 */
	protected Integer getPageNumber(HttpServletRequest request)
	{
		String pageNum=request.getParameter("query.pageNumber");
		if(pageNum!=null&&!pageNum.trim().equals(""))
		{
			return Integer.parseInt(pageNum);
		}
		return 1;
	}
	
	/**
	 * 获得查询条件
	 * @param request
	 * @param queryClass
	 * @return
	 */
	protected <T> T getQuery(HttpServletRequest request,Class<T> queryClass)
	{
		Object target=null;
		try {
			target = queryClass.newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		Enumeration paramets = request.getParameterNames();
		boolean haveSortColumns = false;
		while (paramets.hasMoreElements()) {
			String keys = (String) paramets.nextElement();
			String values="";
			try {
				values = request.getParameter(keys);
				if(request.getMethod().equals("GET"))
				{
					values = new String(values.getBytes("iso-8859-1"),"UTF-8");
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			if (keys.startsWith("query.")) {
				String newKey=keys.substring("query.".length(),keys.length());
				try {
					if(values!=null&&!values.trim().equals(""))
					{
						BeanUtils.setProperty(target, newKey, values);
					}
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
				if (keys.equals("query.sortColumns")) {
					haveSortColumns = true;
				}
			}
		}
		if (!haveSortColumns) {
			try {
				BeanUtils.setProperty(target, "sortColumns", "");
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
		}
		return (T) target;
	}
	
	/**
	 * 保存翻页
	 * @param request
	 * @param page
	 */
	protected void savePageBar(HttpServletRequest request,Page page)
	{
		Map parameter = new HashMap();
		Enumeration paramets = request.getParameterNames();
		boolean haveSortColumns = false;
		while (paramets.hasMoreElements()) {
			String keys = (String) paramets.nextElement();
			String values = request.getParameter(keys);
			if(request.getMethod().equals("GET"))
			{
				try {
					values = new String(values.getBytes("iso-8859-1"),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
			if (keys.startsWith("query.")) {
				parameter.put(keys, values);
				if (keys.equals("query.sortColumns")) {
					haveSortColumns = true;
				}
			}
		}
		if (!haveSortColumns) {
			parameter.put("query.sortColumns", "");
		}
		parameter.put("query.pageSize", page.getPageSize());
		parameter.put("query.pageNumber", page.getPageNum());
		PageBar pageBar = new PageBar(page, parameter);
		request.setAttribute("_pageBar_", pageBar);
		request.setAttribute("page", page);
	}
	
	/**
	 * 获得查询条件查询
	 * @param request
	 * @return
	 */
	protected Map getQueryParams(HttpServletRequest request)
	{
		Map parameter = new HashMap();
		Enumeration paramets = request.getParameterNames();
		boolean haveSortColumns = false;
		while (paramets.hasMoreElements()) {
			String keys = (String) paramets.nextElement();
			String values = request.getParameter(keys);
			if (keys.startsWith("query.")) {
				if(values!=null&&!values.trim().equals(""))
				{
					parameter.put(keys, values);
					if (keys.equals("query.sortColumns")) {
						haveSortColumns = true;
					}
				}
			}
		}
		if (!haveSortColumns) {
			parameter.put("query.sortColumns", "");
		}
		parameter.put("query.pageSize", this.getPageSize(request));
		parameter.put("query.pageNumber", this.getPageNumber(request));
		return parameter;
	}
	
	protected static Hashtable parseQueryString(String s)
	  {
	    String[] valArray = null;
	    if (s == null) {
	      throw new IllegalArgumentException("queryString must not null");
	    }
	    Hashtable ht = new Hashtable();
	    StringBuffer sb = new StringBuffer();
	    StringTokenizer st = new StringTokenizer(s, "&");
	    while (st.hasMoreTokens()) {
	      String pair = st.nextToken();
	      if (pair.trim().length() != 0)
	      {
	        int pos = pair.indexOf('=');
	        if (pos == -1) {
	          throw new IllegalArgumentException("cannot parse queryString:" + s);
	        }
	        String key = parseName(pair.substring(0, pos), sb);
	        String val = parseName(pair.substring(pos + 1, pair.length()), sb);
	        if (ht.containsKey(key)) {
	          String[] oldVals = (String[])ht.get(key);
	          valArray = new String[oldVals.length + 1];
	          for (int i = 0; i < oldVals.length; i++)
	            valArray[i] = oldVals[i];
	          valArray[oldVals.length] = val;
	        } else {
	          valArray = new String[1];
	          valArray[0] = val;
	        }
	        ht.put(key, valArray);
	      }
	    }
	    return fixValueArray2SingleStringObject(ht);
	  }

	  private static Hashtable fixValueArray2SingleStringObject(Hashtable ht)
	  {
	    Hashtable result = new Hashtable();
	    for (Iterator it = ht.entrySet().iterator(); it.hasNext(); ) {
	      Map.Entry entry = (Map.Entry)it.next();
	      String[] valueArray = (String[])entry.getValue();
	      if (valueArray == null)
	        result.put(entry.getKey(), valueArray);
	      else
	        result.put(entry.getKey(), valueArray.length == 1 ? valueArray[0] : valueArray);
	    }
	    return result;
	  }

	  private static String parseName(String s, StringBuffer sb) {
	    sb.setLength(0);
	    for (int i = 0; i < s.length(); i++) {
	      char c = s.charAt(i);
	      switch (c) {
	      case '+':
	        sb.append(' ');
	        break;
	      case '%':
	        try {
	          sb.append((char)Integer.parseInt(s.substring(i + 1, i + 3), 16));

	          i += 2;
	        }
	        catch (NumberFormatException e) {
	          throw new IllegalArgumentException();
	        } catch (StringIndexOutOfBoundsException e) {
	          String rest = s.substring(i);
	          sb.append(rest);
	          if (rest.length() == 2) {
	            i++;
	          }
	        }

	      default:
	        sb.append(c);
	      }
	    }

	    return sb.toString();
	  }
}
